package com.creating.mict.servlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.creating.mict.common.Dom4j;


import java.net.URLEncoder;


public class GetDataServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
//		System.out.println("--------------哈哈1-----------------");
		doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) {
		try {
			InputStream input = req.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String data = recieveData(req);// 接收请求发来的xml消息体
		Dom4j dom4j = new Dom4j();
		dom4j.readLisXmlAndSave(data); //解析并保存数据
		
		//返回信息
		sendReturnDate(resp, "1", "");
	}

	// 接收请求发来的xml消息体
	public static String recieveData(HttpServletRequest request) {
		String inputLine = null;
		// 接收到的数据
		StringBuffer recieveData = new StringBuffer();
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(request
					.getInputStream(), "GBK"));
			while ((inputLine = in.readLine()) != null) {
				recieveData.append(inputLine);
			}
		} catch (IOException e) {
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
			}
		}

		return recieveData.toString();
	}

	

	// 组合xml返回给请求者
	public static void sendReturnDate(HttpServletResponse response,
			String account, String retCode) {
		BufferedWriter out = null;
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"GBK\" ?>");
		sb.append("<ServiceGetData2SPRsp>");
		sb.append("<transactionId>" + retCode + "</transactionId>"); //原值返回
		sb.append("<success>SUCCESS</success>");
		sb.append("<results>");
		sb.append("<result type=\"sms\">");
		sb.append("<title>0</title>"); //0：成功 1：失败
		sb.append("</result>");
		sb.append("</results>");
		sb.append("</ServiceGetData2SPRsp>");
		try {
//			System.out.println("" + sb.toString() + "");
			out = new BufferedWriter(new OutputStreamWriter(response
					.getOutputStream(), "GBK"));
			out.write(sb.toString());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (IOException e) {
				out = null;
			}
		}
	}// 根据参数进行第三服务接口查询，由第三方返回xml

	public static void testPost(String urlStr) {
        try {
            URL url = new URL(urlStr);
            String xmlInfo = getXmlInfo(); //XML文件
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            
            con.setRequestMethod("POST");
            
//            con.setRequestProperty("POST", "http://218.206.93.42:59000/HTTP/1.1");
            con.setRequestProperty("User-Agent", "sp-client");
            con.setRequestProperty("Host", "192.168.1.119:9001");
            
            con.setRequestProperty("Content-Length", Integer.toString(xmlInfo.length()));
            con.setRequestProperty("Content-Type", "text/xml;charset=GBK");
            
            OutputStreamWriter out = new OutputStreamWriter(con
                    .getOutputStream());    
           
//            System.out.println("urlStr=" + urlStr);
//            System.out.println("xmlInfo=" + xmlInfo);
            out.write(new String(xmlInfo.getBytes()));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream()));
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                System.out.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	public static void main(String[] args) {
		String url = "http://127.0.0.1:9001/newmict/GetDataServlet";
		testPost(url);
	}
	
    public static String getXmlInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version = \"1.0\" encoding=\"GBK\"?>\n");
        sb.append("<package>\n");
        sb.append("<transactionId>2012032915572100002</transactionId>\n");
        sb.append("<pushtime>20120329161030</pushtime>\n");
        sb.append("<key>02d79c61978be3aa43665525a57d54b3</key>\n");
        sb.append("<spid>0000</spid>\n");
        sb.append("<serviceid>0000028</serviceid>\n");
        sb.append("<servicetype>3</servicetype>\n");
        sb.append("<feetype>3</feetype>\n");
        sb.append("<paramlist>\n");
        sb.append("<field attribute=\"string\">15105210211,</field>\n");
        sb.append("<field attribute=\"string\">测试短信内容</field>\n");
        
        sb.append("</paramlist>\n");
        sb.append("</package>\n");
       
        return sb.toString();
    }
	
}

